package main

import (
	"fmt"
	"io"
	"net"
	"flag"
	"strconv"
)

var (
	// dst_addr   string = "127.0.0.1:8900" //目标服务器地址
	// local_addr string = "0.0.0.0:8901"   //本地监听地址
	target string
	port int
)

func tcp_handle(tcpConn net.Conn) {
	dst_addr:=target
	remote_tcp, err := net.Dial("tcp", dst_addr) //连接目标服务器
	if err != nil {
		fmt.Println(err)
		return
	}
	// fmt.Printf("'%v' connected by '%v' to '%v'\n", tcpConn.RemoteAddr(),remote_tcp.LocalAddr(),remote_tcp.RemoteAddr())
	fmt.Printf("local tcp:'%v'->'%v', remote tcp: '%v'->'%v'\n", tcpConn.RemoteAddr(), tcpConn.LocalAddr(), remote_tcp.LocalAddr(),remote_tcp.RemoteAddr())
	go io.Copy(remote_tcp, tcpConn)
	go io.Copy(tcpConn, remote_tcp)
}

func tcp_listen() {
	local_addr := "0.0.0.0:"+strconv.Itoa(port)
	ln, err := net.Listen("tcp", local_addr)
	if err != nil {
		fmt.Println("tcp_listen:", err)
		return
	}
	defer ln.Close()
	for {
		tcp_Conn, err := ln.Accept() //接受tcp客户端连接，并返回新的套接字进行通信
		if err != nil {
			fmt.Println("Accept:", err)
			return
		}
		go tcp_handle(tcp_Conn) //创建新的协程进行转发
	}
}

func init(){
	flag.StringVar(&target,"target","","<host>:<port>")
	flag.IntVar(&port,"port",10809,"port")
	flag.Parse()
}

func main() {
	fmt.Println("this is porxy server:")
	fmt.Println("listen on","0.0.0.0:"+strconv.Itoa(port))
	fmt.Println("target:",target)
	go tcp_listen()
	for {
	}
}
